<template>
  <div class="editor_wrapper">
    <div class="head_box">
      <div class="title_box">
        <input type="text" maxlength="60" class="ipt_title" placeholder="请输入标题..." v-model="title" />
        <div class="right_box">
          <!-- 上传封面大图 -->
          <div class="item">
            <Dropdown trigger="click" placement="bottom" class="dropdown_wrapper">
              <i class="iconfont icon-upload-image" :class="{'actved' : screenShot}"></i>
              <div slot="list" class="dropdown_item image_box">
                <p class="title">添加封面大图</p>
                <!-- 上传组件 -->
                <div v-show="!this.screenShot" class="upload_box">
                  <Upload
                    :show-upload-list="false"
                    :max-size="512"
                    :action="upload_url"
                    :data="{token: token}"
                    :before-upload="handleBeforeUpload"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :on-exceeded-size="handleMaxSize"
                    :disabled="disabled_upload"
                    class="upload"
                    ref="upload"
                  >
                    <div class="send_image">
                      <p class="send_tips">{{send_image_flag ? '点击添加图片' : '上传中'}}</p>
                    </div>
                  </Upload>
                </div>
                <!-- 上传后预览 -->
                <div v-show="screenShot" class="screen_preview">
                  <img :src="this.screenShot" class="screen" />
                  <div class="remove_image">
                    <i class="iconfont icon-shanchu" @click="removeImage()"></i>
                  </div>
                </div>
              </div>
            </Dropdown>
          </div>
          <!-- 发布文章 -->
          <div class="item">
            <Dropdown trigger="click" placement="bottom-end" class="dropdown_wrapper">
              <button class="send_btn">发布</button>
              <div slot="list" class="dropdown_item send_box">
                <p class="title">分类</p>
                <CheckBox :options="category_list" :isMultiply="false" @getChoose="getChoose" />
                <p class="send">
                  <button type="button" class="btn" @click="sendContent()">确定并发布</button>
                </p>
              </div>
            </Dropdown>
          </div>
          <!-- 头像 -->
          <div class="item">
            <Dropdown trigger="click" placement="bottom-end" class="dropdown_wrapper">
              <img :src="user.avatar" alt="avatar" class="avatar" />
              <div slot="list" class="dropdown_item user_option">
                <ul>
                  <li class="dropdown-item">
                    <a href>我的主页</a>
                  </li>
                  <li class="dropdown-item">
                    <a href>收藏集</a>
                  </li>
                  <li class="dropdown-item">
                    <a @click="logout()">登出</a>
                  </li>
                </ul>
              </div>
            </Dropdown>
          </div>
        </div>
      </div>
    </div>
    <mavonEditor
      :toolbars="toolbars"
      :ishljs="true"
      :boxShadow="false"
      :tabSize="4"
      :externalLink="externalLink"
      codeStyle="dark"
      fontSize="16px"
      ref="editor"
      @imgAdd="$imgAdd"
      class="editor_box"
    ></mavonEditor>
  </div>
</template>

<script>
import { mapState } from "vuex";
import CheckBox from "./CheckBox";
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
export default {
  name: "editor",
  components: {
    mavonEditor,
    CheckBox
  },
  computed: {
    ...mapState({
      user: state => state.user
    })
  },
  data() {
    return {
      title: "",
      toolbars: {
        imagelink: true, // 图片链接
        help: true, // 帮助
        preview: true // 预览
      },
      externalLink: {
        markdown_css: function() {
          return "/markdown/github-markdown.min.css";
        },
        hljs_js: function() {
          return "/highlightjs/highlight.min.js";
        },
        hljs_css: function(css) {
          return "/highlightjs/styles/" + css + ".min.css";
        },
        hljs_lang: function(lang) {
          return "/highlightjs/languages/" + lang + ".min.js";
        },
        katex_css: function() {
          return "/katex/katex.min.css";
        },
        katex_js: function() {
          return "/katex/katex.min.js";
        }
      },
      //七牛云token
      token: "",
      category_list: [],
      // 选中的分类
      choose: [],
      //封面大图上传地址
      upload_url: "https://upload-z2.qiniup.com",
      //封面大图上传后的地址
      screenShot: "",
      //控制封面大图的上传模块样式显示逻辑
      send_image_flag: true,
      // 控制封面大图预览框显示
      send_box_flag: false,
      //禁止组件上传
      disabled_upload: false
    };
  },

  methods: {
    // 登出
    logout() {
      // 清除token
      localStorage.removeItem("auth");
      location.reload();
    },
    //发表文章
    sendContent() {
      // 发送前应该验证字段内容是否完整
      if (this.title == "" || this.choose == "") {
        this.$Message.error({
          background: true,
          content: "标题和分类不能为空",
          duration: 2.5
        });
      } else {
        this.$axios
          .post("/write", {
            userid: this.user.uid,
            screenshot: this.screenShot,
            title: this.title,
            content: this.$refs.editor.d_render,
            categoryid: this.choose[0].categoryId
          })
          .then(res => {
            alert("发布成功");
            this.$router.push({
              path: "/user/" + this.user.uid
            });
          })
          .catch(err => {
            console.log(err);
          });
      }
    },

    //获取选中项
    getChoose(data) {
      this.choose = JSON.parse(JSON.stringify(data));
    },

    //删除图片
    removeImage() {
      this.screenShot = "";
    },
    //上传前的钩子
    async handleBeforeUpload() {
      await this.$axios
        .post("/qntoken")
        .then(res => {
          this.token = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
      this.send_image_flag = !this.send_image_flag;
      // 禁止再次点击上传
      this.disabled_upload = !this.disabled_upload;
    },

    //上传成功后的钩子
    handleSuccess(res) {
      this.send_image_flag = !this.send_image_flag;
      //此时可以点击上传
      this.disabled_upload = !this.disabled_upload;
      this.screenShot = "http://" + res.fileUrl;
    },
    //上传失败后的钩子
    handleError(err) {
      this.send_image_flag = !this.send_image_flag;
      //此时可以点击上传
      this.disabled_upload = !this.disabled_upload;
      this.$Message.error({
        content: "上传失败，请重试",
        background: true,
        duration: 3
      });
    },

    // 图片大小限制提示
    handleMaxSize(file) {
      this.send_image_flag = !this.send_image_flag;
      //此时可以点击上传
      this.disabled_upload = !this.disabled_upload;
      this.$Message.error({
        content: "图片大小不能超过5M",
        background: true,
        duration: 3
      });
    },

    $imgAdd(pos, $file) {
      let maxsize = 5 * 1024 * 1024;
      if ($file.size > maxsize) {
        this.$Message.error({
          content: "图片大小不能超过5M",
          background: true,
          duration: 3
        });
        //主动删除该图片
        this.$refs.editor.$refs.toolbar_left.$imgDelByFilename($file.name);
        return false;
      } else {
        //先请求qn的上传token
        this.$axios
          .post("/qntoken")
          .then(res => {
            this.token = res.data.data;
            let formdata = new FormData();
            formdata.append("token", this.token);
            formdata.append("file", $file);
            this.$axios({
              url: this.upload_url,
              method: "post",
              data: formdata,
              headers: { "Content-Type": "multipart/form-data", accept: "/" }
            }).then(res => {
              let img_url = "http://" + res.data.fileUrl;
              // 替换图片地址
              this.$refs.editor.$img2Url(pos, img_url);
            });
          })
          .catch(err => {
            console.log(err);
          });
      }
    },

    //获取分类列表
    getCatergoryList() {
      this.$axios
        .get("/getCategoryList")
        .then(res => {
          this.category_list = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  mounted() {
    //监听页面，点击页面空白部分时，隐藏下拉列表
    document.addEventListener("click", this.hiddenDrop);

    this.getCatergoryList();
  }
};
</script>

<style lang='scss'>
.editor_wrapper {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;

  .head_box {
    position: relative;
    line-height: 1;
    .title_box {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      height: 70px;
      .ipt_title {
        flex: 1;
        height: 100%;
        width: 100%;
        border: none;
        outline: none;
        margin-right: 30px;
        padding: 20px;
        font-size: 24px;
        font-weight: 700;
      }
      .right_box {
        display: flex;
        align-items: center;
        .item {
          list-style: none;
          padding: 0 0.7rem;
          .ivu-select-dropdown {
            top: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
            border-radius: 0 !important;
            box-shadow: none !important;
            border: 1px solid #ddd;
            // width: 20rem;
            z-index: 9999;
          }
          .icon-upload-image {
            font-size: 22px;
            color: #a7a7a7;
            cursor: pointer;
          }
          .dropdown_wrapper {
            // 封面图片激活类
            .actved {
              color: #1bb76e;
            }
            //点击显示发布下拉菜单
            .send_btn {
              padding: 0.4rem 1rem;
              border: none;
              outline: none;
              border-radius: 3px;
              font-size: 1rem;
              line-height: 1.1;
              background-color: #1bb76e;
              color: #fff;
              cursor: pointer;
            }

            // 点击用户logo显示下拉菜单
            .avatar {
              width: 40px;
              height: 40px;
              vertical-align: middle;
              object-fit: cover;
              border-radius: 4px;
            }
            // add image box
            .image_box {
              width: 20rem;
              padding: 2rem;
            }

            // send article box
            .send_box {
              width: 20rem;
              padding: 2rem;
            }

            // user option box
            .user_option {
              width: 10rem;
            }
            .dropdown_item {
              // 下拉组件标题
              .title {
                font-size: 1.3rem;
                font-weight: 700;
                color: hsla(218, 9%, 51%, 0.8);
                padding-bottom: 1rem;
              }

              // 大图上传后预览和删除
              .screen_preview {
                position: relative;
                .screen {
                  width: 100%;
                  height: auto;
                }
                .remove_image {
                  position: absolute;
                  top: 0;
                  right: 0;
                  padding: 0.4rem;
                  background-color: rgba(0, 0, 0, 0.5);

                  i {
                    cursor: pointer;
                    color: #ffffff;
                    font-size: 20px;
                  }
                }
                .remove_image:hover {
                  background-color: #000;
                }
              }

              // 发布文章按钮
              .send {
                text-align: center;
                .btn {
                  padding: 0.5rem 1rem;
                  border: 1px solid #1bb76e;
                  outline: none;
                  font-size: 1rem;
                  line-height: 1.2;
                  background-color: #fff;
                  color: #1bb76e;
                  cursor: pointer;
                }
                .btn:hover {
                  background-color: #1bb76e;
                  color: #fff;
                }
              }

              //封面图片上传组件
              .upload_box {
                .upload {
                  .ivu-upload-select {
                    width: 100%;
                    text-align: center;
                  }
                  .send_image {
                    padding: 3rem;
                    cursor: pointer;
                    background-color: #eee;
                    p {
                      font-size: 1.2rem;
                      color: rgba(51, 51, 51, 0.4);
                    }
                  }
                  .send_image:hover {
                    background-color: #ddd;
                  }
                }
              }

              //用户头像下拉菜单
              ul {
                .dropdown-item {
                  text-align: left;
                  list-style: none;
                  a {
                    display: block;
                    color: #71777c;
                    padding: 0.8rem 1.5rem;
                    font-size: 1rem;
                  }
                }
                .dropdown-item:first-child {
                  margin-top: 0.7rem;
                }
                .dropdown-item:last-child {
                  margin-bottom: 0.7rem;
                }

                .dropdown-item:hover {
                  background-color: #eeeeee;
                }
              }
            }
          }
        }
      }
    }
  }
  .editor_box {
    flex: 1;
    min-width: 0%;
    min-height: 0%;
    border: 1px solid #ffffff;
    border-top-color: #ddd;
    flex-direction: column-reverse;

    .scroll-style::-webkit-scrollbar {
      width: 4px !important;
    }
    .v-note-op {
      border-top: 1px solid #ddd !important;
      flex-direction: row-reverse;
      justify-content: flex-end;
      background-color: #fbfbfb !important;
      .v-left-item {
        flex: none;
        span {
          border: none;
        }
        .op-image {
          left: 0px !important;
          top: -90px !important;
          .dropdown-images{
            display: none!important;
          }
        }
      }
      .v-right-item {
        // text-align: left;
        flex: none;
        margin-left: 15px;
      }
    }
    .v-note-show {
      .v-show-content {
        padding-top: 30px !important;
      }
    }
    .v-note-edit {
      .content-input-wrapper {
        padding-top: 30px !important;
      }
    }
  }
}

::-webkit-scrollbar {
  width: 0;
  height: 0;
}
@media screen and (max-width: 375px) {
  .editor_wrapper .head_box .title_box .ipt_title {
    font-size: 20px;
    margin-right: 0;
  }
}
</style>